<template>
  <div>
    <div :id="id"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import merge from 'lodash.merge'

const props = defineProps({
  config: {
    type: Object,
    default: null
  },
  loading: {
    type: Boolean,
    default: true
  }
})

let script
// 脚本标识
const scriptId = 'onlyoffice-editor'
// 异步加载 api.js
const loadScript = () => new Promise((resolve, reject) => {
  const src = import.meta.env.VUE_APP_ONLYOFFICE_API_URL
  console.log(src);
  script = document.querySelector(`#${scriptId}`)
  console.log(script);
  // 加载成功
  const onLoad = () => {
    resolve()
    script.removeEventListener('load', onLoad)
  }
  // 加载失败
  const onError = () => {
    reject(new Error(`脚本 ${src} 加载失败`))
    script.removeEventListener('error', onError)
  }
  if (!script) {
    script = document.createElement('script')
    script.id = scriptId
    script.src = src
    script.addEventListener('load', onLoad)
    script.addEventListener('error', onError)
    document.head.appendChild(script)
  } else if (window.DocsAPI) {
    resolve()
  } else {
    script.addEventListener('load', onLoad)
    script.addEventListener('error', onError)
  }
})

const editor = ref(null)
const id = ref(`editor-${new Date().getTime().toString(32)}`)

const editorConfig = {
  // 编辑器宽度
  width: 1200,
  // 编辑器高度
  height: 600,
  // 编辑器类型，支持 word、cell（表格）、slide（PPT）
  documentType: 'cell',
  // 文档配置
  document: {
    // 权限
    permissions: {
      // 启用评论
      comment: false,
      // 启用下载
      download: true,
      // 启用编辑
      edit: true,
      // 启用导出
      print: true,
      // 启用预览
      review: true
    }
  },
  editorConfig: {
    // 回调地址
    callbackUrl: import.meta.env.VUE_APP_ONLYOFFICE_CALLBACK,
    // 设置语言
    lang: 'zh-CN',
    // customization 字段相关配置详解：https://api.onlyoffice.com/editors/config/editor/customization
    customization: {
      // 强制保存
      forcesave: true,
      features: {
        // 关闭拼写检查
        spellcheck: false
      }
    }
  }
}

const initEditor = async () => {
  try {
    await loadScript()
    createEditor()
  } catch (error) {
    console.error(error)
  }
}

const createEditor = () => {
  if (editor.value) {
    editor.value.destroyEditor()
    editor.value = null
  }
  if (window.DocsAPI) {
    editor.value = new window.DocsAPI.DocEditor(id.value, merge({}, editorConfig, props.config))
  }
}

onMounted(() => {
  if (!props.loading) {
    initEditor()
  }
})

onUnmounted(() => {
  if (editor.value) {
    editor.value.destroyEditor()
    editor.value = null
  }
})

watch(() => props.config, () => {
  initEditor()
}, { deep: true })

watch(() => props.loading, (newLoading) => {
  if (newLoading === false) {
    initEditor()
  }
})
</script>